package com.sky.utils;

import okhttp3.*;
import okhttp3.sse.EventSources;

import java.io.IOException;
import java.net.Proxy;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: 朱海鹏
 * @Package: com.ailight.smart.ai.util
 * @Project: ai-light
 * @date: 2025/3/19 13:08
 * @description :
 */
public class OkHttpUtil {
    private static volatile OkHttpClient okHttpClient;

    public static ConnectionPool connectionPool = new ConnectionPool(10, 5, TimeUnit.MINUTES);

    public static OkHttpClient getInstance() {
        if (okHttpClient == null) { //加同步安全
            synchronized (OkHttpClient.class) {
                if (okHttpClient == null) { //okhttp可以缓存数据....指定缓存路径
                    okHttpClient = new OkHttpClient.Builder()//构建器
                            .proxy(Proxy.NO_PROXY) //来屏蔽系统代理
                            .connectionPool(connectionPool)
                            .connectTimeout(600, TimeUnit.SECONDS)//连接超时
                            .writeTimeout(600, TimeUnit.SECONDS)//写入超时
                            .readTimeout(600, TimeUnit.SECONDS)//读取超时
                            .build();
                    okHttpClient.dispatcher().setMaxRequestsPerHost(200);
                    okHttpClient.dispatcher().setMaxRequests(200);
                }
            }
        }
        return okHttpClient;
    }

    public static String doPost(Map<String, String> mapHeader, String url, String body) {
        OkHttpClient client = getInstance();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType, body);
        Request.Builder builder = new Request.Builder()
                .url(url)
                .post(requestBody);
        mapHeader.forEach(builder::addHeader);
        Request build = builder.build();
        try {
            Response response = client.newCall(build).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
